import { Model } from 'mongoose';

/**
 * T mongo schema
 * V request dto
 */
export class AppService<T, V> {
  appModel: Model<T>;
  constructor(appModel: Model<T>) {
    this.appModel = appModel;
  }

  async detail(id: string): Promise<T> {
    return this.appModel.findById(id).exec();
  }

  async list(filter?: any): Promise<T[]> {
    return this.appModel.find(filter).exec();
  }

  async save(data: V): Promise<any> {
    const document = new this.appModel(data);
    return document.save();
  }

  async delete(id: string): Promise<T> {
    return this.appModel.findByIdAndDelete(id);
  }

  async update(data): Promise<T> {
    await this.appModel.updateOne({ _id: data._id }, data);
    return this.detail(data._id);
  }
}
